<template>
	<view class="page_scroll_view">
		<tn-navbar fixed :bottom-shadow="false">门店资料</tn-navbar>
		<tn-sticky style="box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);">
			<view @click="showPopup=true" class="tn-flex items-center justify-between tn-p">
				<view class="tn-flex items-center">
					<tn-icon name="order" />
					<text class="tn-ml-xs">新增店铺</text>
				</view>
				<tn-icon class="tn-text-right" type="info" name="right" />
			</view>
		</tn-sticky>
		<scroll-view scroll-y="true">
			<view class="tn-p">
				<tn-form :model="storeFormData" label-position="top" ref="storeformRef" :rules="storeFormRules">
					<tn-form-item label="店铺名称" prop="storeName">
						<tn-input v-model="storeFormData.storeName" />
					</tn-form-item>
					<tn-form-item label="店铺号码" prop="storePhone">
						<tn-input v-model="storeFormData.storePhone" />
					</tn-form-item>
					<tn-form-item label="店铺地址" prop="storeAddress">
						<tn-input v-model="storeFormData.storeAddress" />
					</tn-form-item>
					<tn-form-item label="店铺介绍" prop="storeIntro">
						<tn-input v-model="storeFormData.storeIntro" />
					</tn-form-item>
					<tn-form-item label="地理经度" prop="longitude">
						<tn-input v-model="storeFormData.longitude" />
					</tn-form-item>
					<tn-form-item label="地理纬度" prop="latitude">
						<tn-input v-model="storeFormData.latitude" />
					</tn-form-item>
					<tn-form-item label="店铺照片">
						<tn-image-upload v-model="imageList" :custom-upload-callback="uploadCallbackHandle"
							:action="actionUrl" :header="header" @change="change" />
					</tn-form-item>
				</tn-form>
				<view class="tn-mt tn-flex-center">
					<tn-button size="lg" width="80vw" height="80" font-size="26" @click="editForm">修改资料</tn-button>
				</view>
			</view>
		</scroll-view>
	</view>
	<tn-popup v-model="showPopup" open-direction="bottom" height="85vh" close-btn @open="openPopup">
		<view class="tn-p-lg" style="padding-top: 70rpx;">
			<tn-form :model="addFormData.sgymStoreBasicInformation" ref="addformRef" :rules="addFormRules">
				<tn-form-item label="店铺名称" prop="storeName">
					<tn-input v-model="addFormData.sgymStoreBasicInformation.storeName" placeholder="请输入店铺名称" />
				</tn-form-item>
				<tn-form-item label="店铺号码" prop="storePhone">
					<tn-input v-model="addFormData.sgymStoreBasicInformation.storePhone" placeholder="请输入店铺号码" />
				</tn-form-item>
				<tn-form-item label="店铺地址" prop="storeAddress">
					<tn-input v-model="addFormData.sgymStoreBasicInformation.storeAddress" placeholder="请输入店铺地址" />
				</tn-form-item>
				<tn-form-item label="店铺介绍" prop="storeIntro">
					<tn-input v-model="addFormData.sgymStoreBasicInformation.storeIntro" placeholder="请输入店铺介绍" />
				</tn-form-item>
				<tn-form-item label="地理经度" prop="longitude">
					<tn-input v-model="addFormData.sgymStoreBasicInformation.longitude" placeholder="请输入地理经度" />
				</tn-form-item>
				<tn-form-item label="地理纬度" prop="latitude">
					<tn-input v-model="addFormData.sgymStoreBasicInformation.latitude" placeholder="请输入地理纬度" />
				</tn-form-item>
				<tn-form-item label="店铺照片">
					<tn-image-upload v-model="addFormData.storeImageIdList"
						:custom-upload-callback="uploadCallbackHandle2" :action="actionUrl" placeholder="请输入店铺照片"
						:header="header" />
				</tn-form-item>
			</tn-form>
			<view class="tn-mt tn-flex-center">
				<tn-button size="lg" width="80vw" height="80" font-size="26" @click="addForm">新增店铺</tn-button>
			</view>
		</view>
	</tn-popup>
	<tn-modal ref="modalRef" />
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { getStoreInfoApi, getStoreBannerApi, updateStoreInfoApi, updateStoreBannerApi, addStoreApi } from "@/request/user/index.js"
	import { onLoad } from "@dcloudio/uni-app"
	import type { FormRules, TnFormInstance } from '@/uni_modules/tuniaoui-vue3'
	import type { TnModalInstance, ImageUploadCustomCallbackFunction } from '@tuniao/tnui-vue3-uniapp'

	onLoad(() => {
		getStoreInfo()
		getStoreBanner()
	})
	const modalRef = ref(null)
	const currentStoreId = ref(uni.getStorageSync('currentStore'))
	const storeformRef = ref<TnFormInstance>()
	const addformRef = ref<TnFormInstance>()
	const showPopup = ref(false)
	const header = ref({
		storeId: uni.getStorageSync('currentStore'),
		Authorization: 'Bearer ' + uni.getStorageSync('token'),
		filePrefix: "sgym/swiperImage/admin",
		userType: 2,
	})
	const swiperParams = ref([])
	const addFormData = reactive({
		sgymStoreBasicInformation: {
			storeName: '',
			storePhone: '',
			storeAddress: '',
			longitude: '',
			latitude: '',
			storeIntro: '',
			status: 1,
		},
		storeImageIdList: []
	})
	const storeImageIdList = ref([])
	const storeFormData = reactive({
		storeName: '',
		storePhone: '',
		storeAddress: '',
		longitude: '',
		latitude: '',
		storeIntro: '',
		id: '',
		status: 0,
	})
	const imageList = ref<string[]>()
	const actionUrl = 'https://qingmang.sgymlatte.com/api/file/upload'
	const addFormRules : FormRules = {
		storeName: [
			{ required: true, message: '请输入店铺名称', trigger: 'blur' }
		],
		storePhone: [
			{ required: true, message: '请输入店铺号码', trigger: 'blur' }
		],
		storeAddress: [
			{ required: true, message: '请输入店铺地址', trigger: 'blur' }
		],
		longitude: [
			{ required: true, message: '请输入地理经度', trigger: 'blur' }
		],
		latitude: [
			{ required: true, message: '请输入地理纬度', trigger: 'blur' }
		],
		storeIntro: [
			{ required: true, message: '请输入店铺介绍', trigger: 'blur' }
		]
	}
	const storeFormRules : FormRules = {
		storeName: [
			{ required: true, message: '请输入店铺名称', trigger: 'blur' }
		],
		storePhone: [
			{ required: true, message: '请输入店铺号码', trigger: 'blur' }
		],
		storeAddress: [
			{ required: true, message: '请输入店铺地址', trigger: 'blur' }
		],
		longitude: [
			{ required: true, message: '请输入地理经度', trigger: 'blur' }
		],
		latitude: [
			{ required: true, message: '请输入地理纬度', trigger: 'blur' }
		],
		storeIntro: [
			{ required: true, message: '请输入店铺介绍', trigger: 'blur' }
		]
	}

	//自定义返回格式
	const uploadCallbackHandle : ImageUploadCustomCallbackFunction = (
		data : UniApp.UploadFileSuccessCallbackResult
	) => {
		const resData = JSON.parse(data.data)
		swiperParams.value[0].image[resData.result.fileId] = resData.result.imageUrl;
		return resData.result.imageUrl
	}
	//自定义返回格式
	const uploadCallbackHandle2 : ImageUploadCustomCallbackFunction = (
		data : UniApp.UploadFileSuccessCallbackResult
	) => {
		const resData = JSON.parse(data.data)
		storeImageIdList.value.push(resData.result.fileId)
		return resData.result.imageUrl
	}
	// 获取当前门店资料
	const getStoreInfo = () => {
		getStoreInfoApi(currentStoreId.value).then(res => {
			storeFormData.storeName = res.storeName
			storeFormData.storePhone = res.storePhone
			storeFormData.storeAddress = res.storeAddress
			storeFormData.longitude = res.longitude
			storeFormData.latitude = res.latitude
			storeFormData.storeIntro = res.storeIntro
			storeFormData.id = res.id
			storeFormData.status = res.status
		})
	}
	// 获取当前门店的轮播图
	const getStoreBanner = () => {
		getStoreBannerApi(currentStoreId.value).then(res => {
			let arr = []
			res.forEach((item : any) => {
				arr.push(...Object.values(item.image))
			})
			let swiperList = res.map((img : any) => {
				return img.image
			})
			let imageObject = {};
			swiperList.forEach((item : any) => {
				for (let key in item) {
					if (item.hasOwnProperty(key)) {
						imageObject[key] = item[key];
					}
				}
			});
			swiperParams.value = [{
				storeId: currentStoreId.value,
				image: imageObject
			}]
			imageList.value = arr
		})
	}
	// 修改店铺信息
	const updateStoreInfo = () => {
		updateStoreInfoApi(storeFormData).then(res => {
			if (res.code == 0) {
				modalRef.value?.showModal({
					title: '提示',
					content: '修改店铺信息成功',
					confirm: () => {
						getStoreInfo()
						getStoreBanner()
					}
				})
			}
		}).catch(err => {
			modalRef.value?.showModal({
				title: '提示',
				content: err.msg,
			})
		})
	}
	// 修改表单
	const editForm = () => {
		storeformRef.value?.validate((valid) => {
			if (valid) {
				updateStoreInfo()
			} else {
				uni.showToast({
					title: '请检查必填项',
					icon: 'none',
				})
			}
		})
	}
	// 改变轮播图
	const change = (value : Array<string>) => {
		let result = [
			{
				storeId: currentStoreId.value,
				image: {}
			}
		]
		value.forEach(value => {
			for (let key in swiperParams.value[0].image) {
				if (swiperParams.value[0].image.hasOwnProperty(key) && swiperParams.value[0].image[key] === value) {
					result[0].image[key] = value;
				}
			}
		})
		updateStoreBannerApi(result).then(res => {
			if (res.code == 0) {
				uni.showToast({
					title: '修改照片成功',
					success: () => {
						setTimeout(() => {
							getStoreBanner()
						}, 1000)
					}
				})
			}
		}).catch(err => {
			uni.showToast({
				title: err.msg,
				icon: 'error'
			})
		})
	}
	// 新增店铺
	const addStore = () => {
		let obj = {
			sgymStoreBasicInformation: {
				storeName: addFormData.sgymStoreBasicInformation.storeName,
				storePhone: addFormData.sgymStoreBasicInformation.storePhone,
				storeAddress: addFormData.sgymStoreBasicInformation.storeAddress,
				longitude: addFormData.sgymStoreBasicInformation.longitude,
				latitude: addFormData.sgymStoreBasicInformation.latitude,
				storeIntro: addFormData.sgymStoreBasicInformation.storeIntro,
				status: 1,
				id: 0,
				addTime: '',
				endTime: '',
				startTime: '',
				updateTime: ''
			},
			storeImageIdList: storeImageIdList.value
		}
		addStoreApi(obj).then(res => {
			if (res.code == 0) {
				modalRef.value?.showModal({
					title: '提示',
					content: '新增店铺成功',
					confirm: () => {
						showPopup.value = false
					}
				})
			}
		}).catch(err => {
			modalRef.value?.showModal({
				title: '提示',
				content: err.msg,
			})
		})
	}
	// 新增表单
	const addForm = () => {
		addformRef.value?.validate((valid) => {
			if (valid) {
				addStore()
			} else {
				uni.showToast({
					title: '请检查必填项',
					icon: 'none',
				})
			}
		})
	}
	// 新增表单弹出层
	const openPopup = () => {
		addformRef.value?.resetFields()
	}
</script>

<style scoped lang="scss">

</style>